Passed
Pull Request — master (#132)
by
unknown
15:02 queued 06:44
created

QucosaBe.js ➔ ... ➔ $(document).ready   B

Complexity

Conditions 4
Paths 8

Size

Total Lines 76
Code Lines 55

Duplication

Lines 76
Ratio 100 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
cc 4
eloc 55
nc 8
nop 0
dl 76
loc 76
rs 8.4727
c 3
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
/**
2
 * This file is part of the TYPO3 CMS project.
3
 *
4
 * It is free software; you can redistribute it and/or modify it under
5
 * the terms of the GNU General Public License, either version 2
6
 * of the License, or any later version.
7
 *
8
 * For the full copyright and license information, please read the
9
 * LICENSE.txt file that was distributed with this source code.
10
 *
11
 * The TYPO3 project - inspiring people to share!
12
 */
13
14 View Code Duplication
define(['jquery', 'TYPO3/CMS/Dpf/jquery-ui','twbs/bootstrap-datetimepicker'], function($) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
15
16
    var documentListConfirmDialog = function(dialogId) {
17
        $(dialogId).modal({
18
            show: false,
19
            backdrop: 'static'
20
        });
21
        $(dialogId).on('show.bs.modal', function(e) {
22
            $(this).find('#discardDocument').attr('href', $(e.relatedTarget).attr('href'));
23
            var bodyText = $(this).find('.modal-body p').html();
24
            var title = $(e.relatedTarget).attr('data-documenttitle');
25
            $(this).find('.modal-body p').html(bodyText.replace('%s', title));
26
            $(e.relatedTarget).parent().parent().addClass('danger marked-for-removal');
27
        });
28
        $(dialogId).on('hidden.bs.modal', function(e) {
0 ignored issues
show
Unused Code introduced by
The parameter e is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
29
            $('.marked-for-removal').removeClass('danger marked-for-removal');
30
        });
31
    }
32
33
    var datepicker = function() {
34
        $(".datetimepicker").datetimepicker({
35
                useCurrent: false,
36
                keepInvalid: false,
37
                format: "DD.MM.YYYY"
38
        });
39
    }
40
41
    var buttonFillOutServiceUrn = function() {
42
        $('input.urn').each(function() {
43
            var fieldUid = $(this).attr('data-field');
44
            var fieldIndex = $(this).attr('data-index');
45
            var groupUid = $(this).attr('data-group');
0 ignored issues
show
Unused Code introduced by
The variable groupUid seems to be never used. Consider removing it.
Loading history...
46
            var groupIndex = $(this).attr('data-groupindex');
0 ignored issues
show
Unused Code introduced by
The variable groupIndex seems to be never used. Consider removing it.
Loading history...
47
            var fillOutButton = $('.fill_out_service_urn[data-field="' + fieldUid + '"][data-index="' + fieldIndex + '"]');
48
            if (($(this).val() && $(this).val().length > 0) || hasQucosaUrn()) {
49
                fillOutButton.hide();
50
            } else {
51
                fillOutButton.show();
52
            }
53
        });
54
        return false;
55
    }
56
57
    var hasQucosaUrn = function() {
58
        var result = false;
59
        var qucosaUrn = $('#qucosaUrn').val();
60
        $('input.urn').each(function() {
61
            var currentUrn = $(this).val();
62
            if (currentUrn && qucosaUrn && (currentUrn == qucosaUrn)) {
63
                result = result || true;
64
            }
65
        });
66
        return result;
67
    }
68
69
70
    var validateFormAndSave = function() {
71
        $("#validDocument").val("0");
72
        if (validateForm()) {
73
            $("#validDocument").val("1");
74
            $("#new-document-form #save").prop("disabled", true);
75
            $('#new-document-form').submit();
76
            return true;
77
        }
78
        return false;
79
    }
80
81
    var validateFormOnly = function() {
82
        if (validateForm()) {
83
            showFormSuccess();
84
        }
85
        return false;
86
    }
87
88
    var validateForm = function() {
89
        var error = false;
90
        $('span.mandatory-error').remove();
91
        $('div.alert').remove();
92
        $('.tx-dpf-tabs li a').each(function() {
93
            $(this).removeClass('mandatory-error');
94
        });
95
96
        // check mandatory groups
97
        $('fieldset[data-mandatory=1]').each(function() {
98
            var fieldset = $(this);
99
            if (hasMandatoryInputs(fieldset)) {
100
                if (checkMandatoryInputs(fieldset)) {
101
                    $('<div class="alert alert-warning" role="alert"><span class="glyphicon glyphicon glyphicon-warning-sign pull-right"></span>' + form_error_msg_group_mandatory + '</div>').insertAfter(fieldset.find('legend').last());
0 ignored issues
show
Bug introduced by
The variable form_error_msg_group_mandatory seems to be never declared. If this is a global, consider adding a /** global: form_error_msg_group_mandatory */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
102
                    showFormError();
103
                    error = true;
104
                    markPage(fieldset, true);
105
                }
106
            } else {
107
                if (checkFilledInputs(fieldset)) {
108
                    $('<div class="alert alert-warning" role="alert"><span class="glyphicon glyphicon glyphicon-warning-sign pull-right"></span>' + form_error_msg_group_one_required + '</div>').insertAfter(fieldset.find('legend').last());
0 ignored issues
show
Bug introduced by
The variable form_error_msg_group_one_required seems to be never declared. If this is a global, consider adding a /** global: form_error_msg_group_one_required */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
109
                    showFormError();
110
                    error = true;
111
                    markPage(fieldset, true);
112
                    error = true;
113
                }
114
            }
115
        });
116
117
        $('fieldset[id=primary_file]').each(function() {
118
            var fieldset = $(this);
119
            if (checkPrimaryFile(fieldset)) {
120
                $('<div class="alert alert-warning" role="alert"><span class="glyphicon glyphicon glyphicon-warning-sign pull-right"></span>' + form_error_msg_group_mandatory + '</div>').insertBefore(fieldset.find('legend').last());
0 ignored issues
show
Bug introduced by
The variable form_error_msg_group_mandatory seems to be never declared. If this is a global, consider adding a /** global: form_error_msg_group_mandatory */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
121
                showFormError();
122
                error = true;
123
                markPage(fieldset, true);
124
            }
125
        });
126
127
        // check non mandatory groups
128
        $('fieldset[data-mandatory=""]').each(function() {
129
            var fieldset = $(this);
130
            var filledInputs = 0;
131
            $(this).find('.input-field').each(function() {
132
                if ($(this).val() && $(this).attr('data-default') != '1') {
133
                    filledInputs++;
134
                }
135
                $(this).removeClass('mandatory-error');
136
            });
137
138
            // if there are fields with a value then mandatory fields
139
            // are relevant.
140
            if (filledInputs) {
141
                if (checkMandatoryInputs(fieldset)) {
142
                    $('<div class="alert alert-warning" role="alert"><span class="glyphicon glyphicon glyphicon-warning-sign pull-right"></span>' + form_error_msg_group_mandatory + '</div>').insertAfter(fieldset.find('legend').last());
0 ignored issues
show
Bug introduced by
The variable form_error_msg_group_mandatory seems to be never declared. If this is a global, consider adding a /** global: form_error_msg_group_mandatory */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
143
                    showFormError();
144
                    markPage(fieldset, true);
145
                    error = true;
146
                    }
147
                }
148
        });
149
150
        $('fieldset').each(function() {
151
        var fieldset = $(this);
152
        fieldset.find('.input-field').each(function() {
153
            $(this).removeClass('invalid-error');
154
            var validation = $(this).attr('data-regexp');
155
            if ($(this).val() && $(this).val().length > 0 && validation && validation.length > 0) {
156
                try {
157
                    var regexp = new RegExp(validation);
158
                    var res = $(this).val().match(regexp);
159
                    if (!(res && res.length == 1 && res[0] == $(this).val())) {
0 ignored issues
show
Best Practice introduced by
Comparing res.length to 1 using the == operator is not safe. Consider using === instead.
Loading history...
160
                    $('<div class="alert alert-warning" role="alert"><span class="glyphicon glyphicon glyphicon-warning-sign pull-right"></span>' + form_error_msg_field_invalid + ': ' + $(this).attr('data-label') + '</div>').insertAfter(fieldset.find('legend').last());
0 ignored issues
show
Bug introduced by
The variable form_error_msg_field_invalid seems to be never declared. If this is a global, consider adding a /** global: form_error_msg_field_invalid */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
161
                    $(this).addClass('invalid-error');
162
                    showFormError();
163
                    markPage(fieldset, true);
164
                    error = true;
165
                    }
166
                } catch (err) {
167
                    $('<div class="alert alert-warning" role="alert"><span class="glyphicon glyphicon glyphicon-warning-sign pull-right"></span>' + form_error_msg_field_invalid + ': ' + $(this).attr('data-label') + '</div>').insertAfter(fieldset.find('legend').last());
168
                    $(this).addClass('invalid-error');
169
                    showFormError();
170
                    markPage(fieldset, true);
171
                    error = true;
172
                    }
173
            } else {
174
                var validateDate = $(this).attr('data-datatype') == 'DATE';
175
                if ($(this).val() && $(this).val().length > 0 && validateDate && !isDate($(this).val())) {
176
                    $('<div class="alert alert-warning" role="alert"><span class="glyphicon glyphicon glyphicon-warning-sign pull-right"></span>' + form_error_msg_field_invalid + ': ' + $(this).attr('data-label') + '</div>').insertAfter(fieldset.find('legend').last());
177
                    $(this).addClass('invalid-error');
178
                    showFormError();
179
                    markPage(fieldset, true);
180
                    error = true;
181
                }
182
            }
183
184
            var maxLength = $(this).attr('data-maxlength');
185
            if (maxLength && maxLength > 0) {
186
                if ($(this).val().length > maxLength) {
187
                    var max_lengrth_msg = form_error_msg_field_max_length.replace(/%s/gi, maxLength);
0 ignored issues
show
Bug introduced by
The variable form_error_msg_field_max_length seems to be never declared. If this is a global, consider adding a /** global: form_error_msg_field_max_length */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
188
                    $('<div class="alert alert-warning" role="alert"><span class="glyphicon glyphicon glyphicon-warning-sign pull-right"></span>' + max_lengrth_msg + $(this).attr('data-label') + '</div>').insertAfter(fieldset.find('legend').last());
189
                    $(this).addClass('invalid-error');
190
                    showFormError();
191
                    markPage(fieldset, true);
192
                    error = true;
193
                }
194
            }
195
        });
196
        });
197
        return !error;
198
    }
199
200
    var showFormError = function() {
201
        $('.tx-dpf div.alert-danger').remove();
202
        $('<div class="alert alert-danger" role="alert"><span class="glyphicon glyphicon glyphicon-fire pull-right"></span>' + form_error_msg + '</div>').insertBefore($('.tx-dpf form').first());
0 ignored issues
show
Bug introduced by
The variable form_error_msg seems to be never declared. If this is a global, consider adding a /** global: form_error_msg */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
203
        $("html, body").animate({scrollTop: 0}, 200);
204
    }
205
206
    var showFormSuccess = function() {
207
        $('.tx-dpf div.alert-danger').remove();
208
        $('<div class="alert alert-success" role="alert"><span class="glyphicon glyphicon glyphicon-fire pull-right"></span>' + form_success_msg + '</div>').insertBefore($('.tx-dpf form').first());
0 ignored issues
show
Bug introduced by
The variable form_success_msg seems to be never declared. If this is a global, consider adding a /** global: form_success_msg */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
209
        $("html, body").animate({scrollTop: 0}, 200);
210
    }
211
212
    var hasMandatoryInputs = function(fieldset) {
213
        var inputs = fieldset.find(".input-field[data-mandatory=1]");
214
        return inputs.length > 0;
215
    }
216
217
    var markPage = function(fieldset, error) {
218
        var pageId = fieldset.parent().attr('id');
219
        var page = $('.tx-dpf-tabs li a[href=#' + pageId + ']');
220
        if (error) {
221
            page.addClass('mandatory-error');
222
        } else {
223
            page.removeClass('mandatory-error');
224
        }
225
    }
226
227
    var checkMandatoryInputs = function(fieldset) {
228
        var mandatoryError = false;
229
        fieldset.find(".input-field[data-mandatory=1]").each(function() {
230
            var id = $(this).attr('id');
231
            if (($(this).attr('type') != 'checkbox' && !$(this).val()) || ($(this).attr('type') == 'checkbox' && ($("#" + id + ":checked").length != 1 || !$("#" + id + ":checked")))) {
0 ignored issues
show
Best Practice introduced by
Comparing $("#" + id + ":checked").length to 1 using the != operator is not safe. Consider using !== instead.
Loading history...
232
                mandatoryError = mandatoryError || true;
233
                $(this).addClass('mandatory-error');
234
            } else {
235
                $(this).removeClass('mandatory-error');
236
            }
237
        });
238
        return mandatoryError;
239
    }
240
241
    var checkPrimaryFile = function(fieldset) {
242
        var mandatoryError = false;
243
        fieldset.find("input#inp_primaryFile[data-virtual!=1]").each(function() {
244
            if (!$(this).val()) {
245
                mandatoryError = mandatoryError || true;
246
                $(this).addClass('mandatory-error');
247
            } else {
248
                $(this).removeClass('mandatory-error');
249
            }
250
        });
251
        return mandatoryError;
252
    }
253
254
    var checkFilledInputs = function(fieldset) {
255
        var filledInputs = 0;
256
        fieldset.find('.input-field').each(function() {
257
            if ($(this).val()) {
258
                filledInputs++;
259
            }
260
            $(this).removeClass('mandatory-error');
261
        });
262
        return filledInputs < 1;
263
    }
264
265
    var addGroup = function() {
266
        var element = $(this);
267
        // Get the group uid
268
        var dataGroup = $(this).attr('data-group');
269
        // Number of the next group item
270
        var groupIndex = parseInt($(this).attr('data-index')) + 1;
271
        $(this).attr('data-index', groupIndex);
272
        var ajaxURL = $(this).attr('data-ajax');
273
        var params = buildAjaxParams(ajaxURL, "groupIndex", groupIndex);
274
        //do the ajax-call
275
        $.post(ajaxURL, params, function(group) {
276
            var group = $(group).find("fieldset");
277
            // add the new group
278
            $(group)
279
                .css({'display': 'none'})
280
                .insertAfter($('fieldset[data-group="' + dataGroup + '"]').last());
281
282
            var height = $('fieldset[data-group="' + dataGroup + '"]')
283
                .last()
284
                .outerHeight(true)
285
286
            $('html, body')
287
                .animate({scrollTop: element.offset().top - height}, 400, function() {$(group).fadeIn();});
288
289
            buttonFillOutServiceUrn();
290
            datepicker();
291
            addRemoveFileButton();
292
293
            // gnd autocomplete for new groups
294
            var gndField = $(group).find('.gnd');
295
            if (gndField.length != 0) {
0 ignored issues
show
Best Practice introduced by
Comparing gndField.length to 0 using the != operator is not safe. Consider using !== instead.
Loading history...
296
                setGndAutocomplete(gndField.data('field'),gndField.data('groupindex'));
297
            }
298
        });
299
        return false;
300
    }
301
302
    var addField = function() {
303
        var addButton = $(this);
304
        // Get the field uid
305
        var dataField = $(this).attr('data-field');
0 ignored issues
show
Unused Code introduced by
The variable dataField seems to be never used. Consider removing it.
Loading history...
306
        // Number of the next field item
307
        var fieldIndex = parseInt($(this).attr('data-index')) + 1;
308
        $(this).attr('data-index', fieldIndex);
309
        var ajaxURL = $(this).attr('data-ajax');
310
        var params = buildAjaxParams(ajaxURL, "fieldIndex", fieldIndex);
311
        //do the ajax-call
312
        $.post(ajaxURL, params, function(element) {
313
            var field = $(element).find("#new-element").children();
314
            $(field).css({'display': 'none'})
315
                .insertBefore(addButton).fadeIn();
316
            buttonFillOutServiceUrn();
317
            datepicker();
318
319
            // gnd autocomplete for new fields
320
            var gndField = $(group).find('.gnd');
0 ignored issues
show
Bug introduced by
The variable group seems to be never declared. If this is a global, consider adding a /** global: group */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
321
            if (gndField.length != 0) {
0 ignored issues
show
Best Practice introduced by
Comparing gndField.length to 0 using the != operator is not safe. Consider using !== instead.
Loading history...
322
                setGndAutocomplete(gndField.data('field'),gndField.data('groupindex'));
323
            }
324
        });
325
        return false;
326
    }
327
328
    var deleteFile = function() {
329
        var fileGroup = $(this).parent().parent();
330
        var ajaxURL = $(this).attr('data-ajax');
331
        var params = {};
332
        //do the ajax-call
333
        $.post(ajaxURL, params, function(element) {
334
            var field = $(element).find("#new-element").children();
335
            $(fileGroup).replaceWith(field);
336
        });
337
        return false;
338
    }
339
340
    function buildAjaxParams(ajaxURL, indexName, index) {
341
        var res = ajaxURL.match(/(tx\w+?)%/); // get param name
342
        var params = {};
343
        var indexParam = {};
344
        if (res && res[1]) {
345
            indexParam[indexName] = index;
346
            params[res[1]] = indexParam;
347
        }
348
        return params;
349
    }
350
351
    var fillOutServiceUrn = function() {
352
        // Get the field uid
353
        var fieldUid = $(this).attr('data-field');
354
        var fieldIndex = $(this).attr('data-index');
355
        var groupUid = $(this).attr('data-group');
356
        var groupIndex = $(this).attr('data-groupindex');
357
        var ajaxURL = $(this).attr('data-ajax');
358
        var qucosaId = $('#qucosaid').val();
359
        var params = {};
0 ignored issues
show
Unused Code introduced by
The assignment to variable params seems to be never used. Consider removing it.
Loading history...
360
361
        if (qucosaId) {
362
            params = buildAjaxParams(ajaxURL, "qucosaId", qucosaId);
363
        } else {
364
            params = buildAjaxParams(ajaxURL, "qucosaId", "");
365
        }
366
367
        var group = $(this).closest(".fs_group");
368
369
        //do the ajax-call
370
        $.getJSON(ajaxURL, params, function(element) {
371
372
            group.find('.alert-filloutservice-urn').remove();
373
374
            if (element.error) {
375
                var errorMsg = $('<div class="alert alert-danger alert-filloutservice-urn" role="alert"><span class="glyphicon glyphicon glyphicon-fire pull-right"></span>' + form_error_msg_filloutservice + '</div>');
0 ignored issues
show
Bug introduced by
The variable form_error_msg_filloutservice seems to be never declared. If this is a global, consider adding a /** global: form_error_msg_filloutservice */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
376
                errorMsg.insertAfter(group.find('legend'));
377
                $("html, body").animate({scrollTop: group.offset().top}, 200);
378
            } else {
379
                $('#qucosaid').val(element.qucosaId);
380
                $('#qucosaUrn').val(element.value);
381
                var inputField = $('.input-field[data-field="' + fieldUid + '"][data-index="' + fieldIndex + '"][data-group="' + groupUid + '"][data-groupindex="' + groupIndex + '"]');
382
                inputField.val(element.value);
383
                buttonFillOutServiceUrn();
384
            }
385
        });
386
        return false;
387
    }
388
389
    var continuousScroll = function() {
390
        var ajaxURL = $("#next").attr('href');
391
        $.ajax({
392
            url: ajaxURL,
393
            success: function(html) {
394
                if (html) {
395
                    $(html).find("table tbody tr").each(function() {
396
                        $("#search-results tbody tr").last().parent().append(this);
397
                    });
398
                    if ($(html).find("table tbody tr").length <= 0) {
399
                        $("#next").hide();
400
                    }
401
                } else {
402
                    $("#next").hide();
403
                }
404
            }
405
        });
406
        return false;
407
    }
408
409
    var isDate = function(value) {
410
        if (value == '') return false;
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
411
        var rxDatePattern = /^(\d{1,2})(\.)(\d{1,2})(\.)(\d{4})$/; //Declare Regex
412
        var dtArray = value.match(rxDatePattern); // is format OK?
413
        if (dtArray == null) return false;
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
Best Practice introduced by
Comparing dtArray to null using the == operator is not safe. Consider using === instead.
Loading history...
414
        //Checks for mm/dd/yyyy format.
415
        var dtMonth = dtArray[3];
416
        var dtDay = dtArray[1];
417
        var dtYear = dtArray[5];
418
        if (dtMonth < 1 || dtMonth > 12) {
419
            return false;
420
        }
421
        if (dtDay < 1 || dtDay > 31) {
422
            return false;
423
        }
424
        if ((dtMonth == 4 || dtMonth == 6 || dtMonth == 9 || dtMonth == 11) && dtDay == 31) {
425
            return false;
426
        }
427
        if (dtMonth == 2) {
428
            var isleap = (dtYear % 4 == 0 && (dtYear % 100 != 0 || dtYear % 400 == 0));
0 ignored issues
show
Best Practice introduced by
Comparing dtYear % 100 to 0 using the != operator is not safe. Consider using !== instead.
Loading history...
Best Practice introduced by
Comparing dtYear % 4 to 0 using the == operator is not safe. Consider using === instead.
Loading history...
Best Practice introduced by
Comparing dtYear % 400 to 0 using the == operator is not safe. Consider using === instead.
Loading history...
429
            if (dtDay > 29 || (dtDay == 29 && !isleap)) return false;
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
430
        }
431
        return true;
432
    }
433
434
    function addRemoveFileButton() {
435
        $('.rem_file').unbind('click');
436
        $('.rem_file').bind('click', function (evt) {
437
            evt.preventDefault();
438
            $(this).siblings('.input_file_upload').val('');
439
        });
440
    }
441
442
    function gndNothingFound(fieldId, groupIndex) {
443
        var gndInputField = $('.gnd[data-field="' + fieldId + '"][data-groupindex="' + groupIndex + '"]');
444
445
        if (gndInputField.data('old_gnd_field_value')) {
446
            gndInputField.val(gndInputField.data('old_gnd_field_value'));
447
        } else {
448
            gndInputField.val();
449
        }
450
451
        var gndFieldId = gndInputField.data('gndfield');
452
        var linkedGroupIndex = gndInputField.data('groupindex');
453
        var gndLinkedInputField = $('input[data-field="' + gndFieldId + '"][data-groupindex="' + linkedGroupIndex + '"]');
454
455
        if (gndLinkedInputField.data('old_gnd_field_id')) {
456
            gndLinkedInputField.val(gndLinkedInputField.data('old_gnd_field_id'));
457
        } else {
458
            gndLinkedInputField.val();
459
        }
460
461
        /** global: form_error_msg_nothing_found */
462
        $('<div id="gnd-nothing-found" class="alert alert-warning" role="alert"><span class="glyphicon glyphicon glyphicon-fire pull-right"></span>' + form_error_msg_nothing_found + '</div>').insertBefore(gndInputField.closest('.form-container'));
0 ignored issues
show
Bug introduced by
The variable form_error_msg_nothing_found seems to be never declared. If this is a global, consider adding a /** global: form_error_msg_nothing_found */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
463
464
        gndInputField.bind("keypress click", function () {
465
            $("#gnd-nothing-found").remove();
466
        });
467
468
        gndLinkedInputField.bind("keypress click", function () {
469
            $("#gnd-nothing-found").remove();
470
        });
471
472
    }
473
474
    function setGndAutocomplete(fieldId, groupIndex) {
475
        // GND autocomplete
476
        var ajaxURL = $('.gnd[data-field="' + fieldId + '"][data-groupindex="' + groupIndex + '"]').attr('data-ajax');
477
478
        var gndInputField = $('.gnd[data-field="' + fieldId + '"][data-groupindex="' + groupIndex + '"]');
479
        var gndFieldId = gndInputField.data('gndfield');
480
        var linkedGroupIndex = gndInputField.data('groupindex');
481
        var gndLinkedInputField = $('input[data-field="' + gndFieldId + '"][data-groupindex="' + linkedGroupIndex + '"]');
482
483
        gndInputField.attr('data-old_gnd_field_value',gndInputField.val());
484
        gndLinkedInputField.attr('data-old_gnd_field_id',gndLinkedInputField.val());
485
486
        // Get the name of the parameter array (tx_dpf_...),
487
        // the name depends on whether the call is from the frontend or the backend
488
        var res = ajaxURL.match(/(tx_dpf\w+?)%/);
489
        var paramName = "tx_dpf_qucosaform[search]";
490
        if (res && res[1]) {
491
            paramName = res[1]+"[search]";
492
        }
493
494
        $('.gnd[data-field="' + fieldId + '"][data-groupindex="' + groupIndex + '"]').autocomplete({
495
            source: function (request, response) {
496
497
                $('input[data-field="' + gndFieldId + '"][data-groupindex="' + linkedGroupIndex + '"]').val('');
498
499
                var requestData = {};
500
                requestData[paramName] = request.term.replace(" ", "+");
501
                $.ajax({
502
                    type: 'POST',
503
                    url: ajaxURL,
504
                    data: requestData,
505
                    dataType: 'json',
506
                    timeout: 10000,
507
                    success: function (data) {
508
                        if (data) {
509
                            response(data);
510
                        } else {
511
                            gndNothingFound(fieldId, groupIndex);
512
                            response([]);
513
                        }
514
                    },
515
                    error: function () {
516
                        gndNothingFound(fieldId, groupIndex);
517
                        response([]);
518
                    }
519
                });
520
            },
521
            minLength: 3,
522
            select: function (event, ui) {
523
                gndFieldId = $(event.target).data('gndfield');
524
                linkedGroupIndex = $(event.target).data('groupindex');
525
                $('input[data-field="' + gndFieldId + '"][data-groupindex="' + linkedGroupIndex + '"]').val(ui.item.gnd);
526
            },
527
        }).autocomplete( "instance" )._renderItem = function( ul, item ) {
528
            return $( "<li>" )
529
                .append( "<div class='gnd-autocomplete'><span class='gnd-value' style='display:none;'>" + item.value + "</span>" +
530
                    "<span class='gnd-label'>" + item.label + "</span></div>"
531
                )
532
                .appendTo( ul );
533
        };
534
    }
535
536
    var previousNextFormPage = function() {
537
538
        $('.prev-next-buttons button').click(function (e) {
539
            var activePage = $('.tx-dpf-tabs').find('li.active');
540
            var newActivePage = activePage;
0 ignored issues
show
Unused Code introduced by
The assignment to variable newActivePage seems to be never used. Consider removing it.
Loading history...
541
542
            if ($(this).attr('id') == 'next-form-page') {
543
                newActivePage = activePage.next();
544
            } else {
545
                newActivePage = activePage.prev();
546
            }
547
548
            if (newActivePage.length > 0) {
549
                activePage.removeClass('active');
550
                activePage.find('a').attr('aria-expanded', 'false');
551
                $('.tab-content').find('div.active').removeClass('active');
552
553
                newActivePage.addClass('active');
554
                newActivePage.find('a').attr('aria-expanded', 'true');
555
                $('.tab-content').find(newActivePage.find('a').attr('href')).addClass('active');
556
557
                updatePrevNextButtons(newActivePage);
558
559
                $('html, body').animate({
560
                    scrollTop:$('.tx-dpf').offset().top
561
                },'fast');
562
            }
563
564
            e.preventDefault();
565
566
        });
567
568
        updatePrevNextButtons($('.tx-dpf-tabs li.active'));
569
570
        $('.tx-dpf-tabs li').click(function(){
571
            updatePrevNextButtons($(this));
572
        });
573
574
    }
575
576
    var updatePrevNextButtons = function(activePage) {
577
578
        if (activePage.prev().length < 1) {
579
            $('#prev-form-page').addClass('disabled');
580
        } else {
581
            $('#prev-form-page').removeClass('disabled');
582
        }
583
        if (activePage.next().length < 1) {
584
            $('#next-form-page').addClass('disabled');
585
        } else {
586
            $('#next-form-page').removeClass('disabled');
587
        }
588
    }
589
590
    var inputWithOptions = function() {
591
592
        $.widget( "custom.dropdownoptions", {
593
            _create: function() {
594
595
                var availableTags = [];
596
                var test = this.element
0 ignored issues
show
Unused Code introduced by
The variable test seems to be never used. Consider removing it.
Loading history...
597
                    .closest(".dropdown-options")
598
                    .find(".dropdown-options-values li")
599
                    .each(function(){
600
                        if ($(this).text().length > 0) {
601
                            availableTags.push($(this).text());
602
                        }
603
                    });
604
605
                this.element
606
                    .addClass( ".dropdown-options-input" )
607
                    .autocomplete({
608
                        minLength: 0,
609
                        source: availableTags
610
                    });
611
612
                this._createShowAllButton();
613
            },
614
            _createShowAllButton: function() {
615
616
                var input = this.element;
617
618
                wasOpen = false;
0 ignored issues
show
Bug introduced by
The variable wasOpen seems to be never declared. Assigning variables without defining them first makes them global. If this was intended, consider making it explicit like using window.wasOpen.
Loading history...
619
620
                input
621
                    .closest(".dropdown-options")
622
                    .find(".dropdown-options-toggle")
623
                    .on( "mousedown", function() {
624
                        wasOpen = input.autocomplete( "widget" ).is( ":visible" );
0 ignored issues
show
Bug introduced by
The variable wasOpen seems to be never declared. Assigning variables without defining them first makes them global. If this was intended, consider making it explicit like using window.wasOpen.
Loading history...
625
                    })
626
                    .on( "click", function() {
627
                        input.trigger( "focus" );
628
                        if ( wasOpen ) {
629
                            return;
630
                        }
631
                        input.autocomplete( "search", "" );
632
633
                    });
634
                input
635
                    .on( "click", function() {
636
                        input.autocomplete( "search", "" );
637
                    });
638
            }
639
        });
640
641
        $( ".dropdown-options-input" ).dropdownoptions();
642
    }
643
644
    $(window).scroll(function() {
645
        if ($(this).scrollTop() > 330) {
646
            $(".tx-dpf-tab-container").addClass("sticky");
647
        } else {
648
            $(".tx-dpf-tab-container").removeClass("sticky");
649
        }
650
    });
651
652
    $(document).ready(function() {
653
        $('#new-document-form').trigger('reset');
654
        documentListConfirmDialog('#confirmDiscard');
655
        documentListConfirmDialog('#confirmPublish');
656
        documentListConfirmDialog('#confirmUpdate');
657
        documentListConfirmDialog('#confirmActivate');
658
        documentListConfirmDialog('#confirmInactivate');
659
        documentListConfirmDialog('#confirmRestore');
660
        documentListConfirmDialog('#confirmDelete');
661
662
        datepicker();
663
664
        $('[data-toggle="tooltip"]').tooltip();
665
        var $disableForm = $('form[data-disabled]').attr('data-disabled');
666
        if ($disableForm) {
667
            $('.input-field').each(function() {$(this).attr('disabled', 'disabled');});
668
            $('.rem_file_group').each(function() {$(this).attr('disabled', 'disabled');});
669
            $('.add_file_group').each(function() {$(this).attr('disabled', 'disabled');});
670
            $('.input_file_upload').each(function() {$(this).attr('disabled', 'disabled');});
671
            $('.add_field').each(function() {$(this).attr('disabled', 'disabled');});
672
            $('.add_group').each(function() {$(this).attr('disabled', 'disabled');});
673
            $('.rem_field').each(function() {$(this).attr('disabled', 'disabled');});
674
            $('.rem_group').each(function() {$(this).attr('disabled', 'disabled');});
675
            $('.fill_out_service_urn').each(function() {$(this).attr('disabled', 'disabled');});
676
        }
677
678
        buttonFillOutServiceUrn();
679
680
        $(".tx-dpf").on("click", ".rem_group", function() {
681
            $(this).parents('fieldset').fadeOut(300, function() {$(this).remove();});
682
            return false;
683
        });
684
        $(".tx-dpf").on("click", ".rem_file_group", deleteFile);
685
        $(".tx-dpf").on("click", ".rem_secondary_upload", function() {
686
            var dataIndex = $(this).data("index");
0 ignored issues
show
Unused Code introduced by
The variable dataIndex seems to be never used. Consider removing it.
Loading history...
687
            $(this).parents('.fs_file_group').fadeOut(300, function() {$(this).remove();});
688
            return false;
689
        });
690
        $(".tx-dpf").on("click", ".rem_field", function() {
691
            var dataIndex = $(this).data("index");
0 ignored issues
show
Unused Code introduced by
The variable dataIndex seems to be never used. Consider removing it.
Loading history...
692
            var dataField = $(this).data("field");
0 ignored issues
show
Unused Code introduced by
The variable dataField seems to be never used. Consider removing it.
Loading history...
693
            $(this).parents('.form-group').fadeOut(300, function() {$(this).remove();});
694
            return false;
695
        });
696
        // Add metadata group
697
        $(".tx-dpf").on("click", ".add_group", addGroup);
698
        $(".tx-dpf").on("click", ".add_file_group", addGroup);
699
        $(".tx-dpf").on("click", ".add_field", addField);
700
        $(".tx-dpf").on("click", ".fill_out_service_urn", fillOutServiceUrn);
701
        $(".tx-dpf").on("keyup", "input.urn", buttonFillOutServiceUrn);
702
        $(".tx-dpf").on("click", "#next", continuousScroll);
703
        $(".form-submit").on("click", "#save", validateFormAndSave);
704
        $(".form-submit").on("click", "#validate", validateFormOnly);
705
706
        // hide 'more results' link
707
        var countResults = $('#search-results :not(thead) tr').length;
708
        var resultCount = $('#next').data('resultCount');
709
710
        if (countResults < resultCount) {
711
            $("#next").hide();
712
        }
713
714
        addRemoveFileButton();
715
716
        previousNextFormPage();
717
718
        var gnd = $('.gnd');
719
        if(gnd.length > 0) {
720
            gnd.each(function() {
721
                setGndAutocomplete($(this).data("field"),  $(this).data("groupindex"));
722
            });
723
        }
724
725
        inputWithOptions();
726
727
    });
728
});
729
730